/**
 * Created by xinguoren on 15-4-16.
 */

var fs = require("fs");
var mongoService = require("../services/mongoService");
var async = require("async");
exports.picPreview = function (req, res) {
    res.render("picPreview");
};

exports.uploadPage = function (req, res) {
    var user = req.session.user;
    if(!user || !user.id){
        return res.end("<script>parent.window.loginSuccess(false,null);parent.document.getElementById('userLoginFlag').value='';</script>");
    }
    res.render("fileUpload");
};

function saveFile(user, file, callback) {
    var nowTime = (new Date()).getTime();
    var dbquery = {
        collection: "uploadFiles",
        insert: {
            fileName: file.name,
            size: file.size,
            path: file.path,
            type: file.type,
            uptime: nowTime,
            lastModified: file.lastModifiedDate,
            userid: user.id
        }
    };
    console.log("insert mongo ssss",dbquery);
    mongoService.insertMongo(dbquery, function (result) {
        if (result === "insert error"){
            callback("error");
        } else {
            callback(null);
        }
    });
};
function removeFile( file, user){
    try{
        fs.unlink(file.path,function(err){
            console.log("remove file ",err);
            if(err){
                return {file:false};
            }else{
                if(user){
                    mongoService.deleteMongo({userid:user.id,fileName:file.name,size:file.size,lastModified:file.lastModifiedDate},function(err){
                        if(err === "delete error"){
                            return {file:true,mongo:false};
                        }else{
                            return {file:true,mongo:true};
                        }
                    });
                }else{
                    return {file:true};
                }
            }
        });
    }catch (e){}
};
exports.upload = function (req, res) {
    var user = req.session.user;
    var files = [];
    for (var file in  req.files) {
        files.push(req.files[file]);
    }
    if(!user || !user.id){
      user = {};
      user.nologinFlag = true;
    }
    var datas = req.body;
    if (files !== []) {
        var i = 0;
        async.whilst(
            function () {
                return i < files.length
            },
            function (callback) {
                i++;
                if(!user.nologinFlag){
                    saveFile(user, files[i - 1], callback);
                }else{
                    removeFile(files[i-1],null);
                    callback(null);
                }
            },
            function (err) {
                if (err) {
                    console.log("error", err);
                } else {
                    console.log("success");
                }
                if(user.nologinFlag){
                    delete user.nologinFlag;
                    return  res.end("novalidate user");
                }
                res.end("ok");
            }
        )
    } else {
        res.end("??")
    }
};

